# _*_ coding:utf-8 _*_

# 1.自定义一个异常类, 当list内元素长度超过10的时候抛出异常

class MyError(Exception):
    def __init__(self,message):
        self.message = message

    def __str__(self):
        return self.message
def fun(a_list):
    try:
        if len(a_list) > 10:
            raise MyError('列表长度超过10')
    except Exception as e:
        print(e)


a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
fun(a_list)
# 2.思考如果对于多种不同的代码异常情况都要处理,又该如何去处理,自己写一个小例子
try:
    # print(100/0)
    # print(a)
    # file = open('txt.txt','r')
    _list = [1,3,3,5]
    _list[8]
    print('发生异常了，赶快去捕获处理')
    pass
except NameError as e:
    print('NameError:%s' % e)
except IOError as e:
    print('IOError:%s' % e)
except ZeroDivisionError as e:
    print('ZeroDivisionError:%s' % e)
except SyntaxError as e:
    print('SyntaxError:%s' % e)
except IndexError as e:
    print('IndexError:%s' % e)
except KeyError as e:
    print('KeyError:%s' % e)
except AttributeError as e:
    print('AttributeError:%s' % e)

# 3.try-except和try-finally有什么不同,写例子理解区别
def fun1():
    '''
    try-except:只有try发生异常时，才会执行except
    :return:
    '''
    try:
        100 / 0
    except Exception as e:
        print(e)


def fun2():
    '''
    try-finally:不管有没有发生异常，都会执行
    :return:
    '''
    try:
        100 / 0
    finally:
        print('finally')


# fun1()
# fun2()
# 4.写函数，检查传入字典的每一个value的长度，如果大于2，
# 那么仅仅保留前两个长度的内容，并将新内容返回给调用者
# dic = {“k1”: "v1v1","k2":[11,22,330}

def fun3(a_dict):
    new_list = []
    for value in a_dict.values():
        if len(value) > 2:
            if isinstance(value, str):
                new_list.append(value[:2])
            elif isinstance(value, list):
                new_list.extend(value[:2])
    return new_list


dic = {'k1': 'v1v1', 'k2': [11, 22, 33]}
new_list = fun3(dic)
print(new_list)